package com.changge.common.mq.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.changge.common.core.constant.HttpConst;
import com.changge.common.mq.service.IRabbitService;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * RabbitMQ生产者操作接口模板
 *
 * @author zhangrongkang
 * @since 2023/10/24
 */
@Slf4j
@Service
public abstract class AbstractProducer implements IRabbitService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 交换机
     */
    @Setter
    private String exchange;

    /**
     * 路由
     */
    @Setter
    private String routingKey;

    /**
     * 发送消息方法
     *
     * @param message 消息对象
     */
    @Override
    public void sendMessage(Object message) {
        // 在发送消息之前对消息进行后处理
        MessagePostProcessor messagePostProcessor = (msg) -> {
            // 获取了消息对象属性
            MessageProperties messageProperties = msg.getMessageProperties();
            // 设置消息唯一表示与时间
            messageProperties.setMessageId(IdUtil.randomUUID());
            messageProperties.setTimestamp(new Date());
            return msg;
        };
        // 构建消息内容
        MessageProperties messageProperties = new MessageProperties();
        // 设置编码格式和数据格式为纯文本
        messageProperties.setContentEncoding(HttpConst.UTF_8);
        messageProperties.setContentType(HttpConst.TEXT_PLAIN);
        // 获取消息主体内容
        String data = JSONUtil.toJsonStr(message);
        // 构建Message对象
        Message msg = new Message(data.getBytes(StandardCharsets.UTF_8), messageProperties);
        // 发送消息
        rabbitTemplate.convertAndSend(this.exchange, this.routingKey, msg, messagePostProcessor);
    }

}
